<template>
  <div class="figma-card-container">
    <div class="card-background">
      <div class="title">
        <div class="bus-icon">
          <img src="@/assets/CampusBus/bus-icon1.svg" alt="bus-icon1" />
        </div>
        <div class="start-stop">潍坊</div>
        <div class="arrow-icon">
          <img src="@/assets/CampusBus/card/箭头/image.png" alt="jiantou" />
        </div>
        <div class="start-stop">青州</div>
      </div>
      <div v-for="item in cardData" :key="item.id" class="card-item-wrapper">
        <div class="bus-info">
          <span class="info-value">{{ getTimeOfDay(item.tBusSchedule.line) }} </span
          ><span class="info-item"
            >车牌: <span class="info-value">{{ item.tBus.licensePlate }}</span></span
          >
          <span class="info-item"
            >荷载: <span class="info-value">{{ item.tBus.maxCapacity }}</span></span
          >
        </div>
    
        <el-button v-if="ReservationList.some(res => res.dateId === item.id&&res.reservationStatus===1)" type="success" size="small" 
          >已预约</el-button
        >
        <el-button v-else-if="ReservationList.some(res => res.dateId === item.id&&res.reservationStatus===2)" type="info" size="small" 
          >候补中</el-button
        >
        <el-button v-else type="primary" size="small" @click="handleReservation(item)"
          >预约</el-button
        >

        <el-dialog v-model="dialogVisible" title="确认预约" width="80%" center>
          <el-form>
            <!-- 移除固定 label-width，使其在手机屏幕上更具响应性 -->
            <el-form-item label="姓名:">
              <el-input
                v-model="teacherStore.teacherInfo.realname"
                :disabled="true"
              ></el-input>
            </el-form-item>
            <el-form-item label="工号:">
              <el-input
                v-model="teacherStore.teacherInfo.teacherCode"
                :disabled="true"
              ></el-input>
            </el-form-item>
            <el-form-item label="电话:">
              <el-input
                v-model="teacherStore.teacherInfo.phone"
                :disabled="true"
              ></el-input>
            </el-form-item>
            <el-form-item label="学院:">
              <el-input
                v-model="teacherStore.teacherInfo.collegeName"
                :disabled="true"
              ></el-input>
            </el-form-item>
          </el-form>
          <span>请选择是否有课：</span>
          <el-radio-group v-model="selectedIsClass">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="2">否</el-radio>
          </el-radio-group>
          <template #footer>
            <span class="dialog-footer">
              <el-button @click="dialogVisible = false">取消</el-button>
              <el-button type="primary" @click="confirmReservation"> 确认 </el-button>
            </span>
          </template>
        </el-dialog>
      </div>
    </div>
  </div>
</template>

<script setup>
// 定义组件接收的 props
defineProps(["cardData"]);

/**
 * @description 根据行号判断是上午还是下午
 * @param {number} line - 行号
 * @returns {string} - 上午或下午
 */
const getTimeOfDay = (line) => {
  if (line === 1 || line === 3) {
    return "上午";
  } else if (line === 2 || line === 4) {
    return "下午";
  }
  return "未知"; // 或者可以返回一个默认值，例如 '未知'
};

// 预约按钮点击事件处理函数
import { addReservation } from "@/api/busmanagement/reservation";
import { useTeacherStore } from "@/store/modules/teacher";
import { ElMessage } from "element-plus";
import { ref, onMounted } from "vue";
import { listReservation } from "@/api/busmanagement/reservation";
const teacherStore = useTeacherStore();

onMounted(() => {
  teacherStore.fetchTeacherInfo();
  queryReservation();
});
const ReservationList = ref([]);
// 控制弹窗显示隐藏
const dialogVisible = ref(false);
// 存储当前选中的预约项
const selectedItem = ref(null);
// 存储用户选择的isClass，默认为1 (是)
const selectedIsClass = ref(1);

// 预约状态缓存，避免重复请求
const reservationStatusCache = ref(new Map());

const handleReservation = (item) => {
  console.log("预约按钮点击，当前项:", item);
  selectedItem.value = item;
  dialogVisible.value = true;
};

// 确认预约
const confirmReservation = async () => {
  if (!selectedItem.value) {
    ElMessage.error("未选择预约项");
    return;
  }
  try {
    const data = {
      dateId: selectedItem.value.id,
      realname: teacherStore.teacherInfo.realname,
      teacherCode: teacherStore.teacherInfo.teacherCode,
      phone: teacherStore.teacherInfo.phone,
      collegeName: teacherStore.teacherInfo.collegeName,
      isClass: selectedIsClass.value,
    };
    await addReservation(data);
    ElMessage.success("预约成功");
    queryReservation();
    // 预约成功后，更新缓存中的状态
    reservationStatusCache.value.set(selectedItem.value.id, 1);

    // 可以根据需要添加刷新列表或其他操作
  } catch (error) {
    ElMessage.error("预约失败，请稍后再试");
    console.error("预约失败:", error);
  } finally {
    dialogVisible.value = false;
    selectedItem.value = null;
    selectedIsClass.value = 1; // 重置为默认值
  }
};

// 根据工号和日期查询预约信息（保留原方法，但不再在模板中直接调用）
const queryReservation = async () => {
  try {
    await teacherStore.fetchTeacherInfo();
    console.log("开始查询预约信息，教师工号:", teacherStore.teacherInfo.teacherCode);
    const response = await listReservation({
      teacherCode: teacherStore.teacherInfo.teacherCode,
    });
    
    // 打印完整的响应数据，以便调试
    console.log("API响应完整数据:", response);
    
    // 检查响应数据结构
    if (response && response.code === 200) {
      ReservationList.value = response.rows;
      console.log("预约信息列表:", ReservationList.value);
    } 
  } catch (error) {
    
  }
};
</script>

<style scoped>
.figma-card-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 99%;
  /* height: 188px; */
  background-color: #ffffff; /* Component 1 的背景色 */
  border-radius: 5px; /* Rectangle 6 的圆角 */
  /* overflow: hidden; */
  margin: 0 0 20px 0;
}

.card-item-wrapper {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  padding: 0 10px;
  margin-bottom: 10px; /* 根据需要调整间距 */
}

.card-background {
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  width: 100%;
  height: 100%;
  background-color: #ffffff; /* Rectangle 6 的背景色 */
  border-radius: 5px;
}

.title {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: center;
  width: 100%;
  padding: 10px 0;
  height: auto;
}

.bus-icon {
  margin-right: 10px; /* 让图标整体靠左一些 */
}

.start-stop {
  font-weight: 300;
  font-size: 14px;
  color: #000000; /* 假设文本颜色为黑色，Figma数据中未明确给出 */
}

.arrow-icon {
  transform: scale(0.4);
  width: 40%;
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: center;
}

.bus-info {
  display: flex;
  align-items: center;
  padding: 5px 0;
  font-size: 12px;
  height: 50px;
}

.info-item {
  margin: 0 5px;
}

.info-value {
  font-weight: bold;
  color: #337ecc; /* Element UI primary color */
}
</style>
